package com.kunpan.admin.common.redis;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.kunpan.admin.common.Enum.BusinessType;
import com.kunpan.admin.common.satoken.SaTokenUtils;
import com.kunpan.admin.constant.Constants;
import com.kunpan.admin.constant.RedisMessage;
import com.kunpan.admin.entity.User;
import com.kunpan.admin.entity.dto.MessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;


/**
 * 消息接收类
 */
@Component
public class RedisMessageReceiver {
    private static final Logger logger = LoggerFactory.getLogger(RedisMessageReceiver.class);

    @Autowired
    private RedisCache redisCache;

    /**
     * 处理文件上传完成消息
     *
     * @param message 格式示例："CACHE_KEY:file_list:user123"
     */
    public void handleMessage(Object message) {
        logger.info("收到消息对象: {}", message);
//        byte[] body = message.getBody();
        MessageDto messageDto = (MessageDto) message;
        //进行删除文件信息缓存操作
        if (messageDto.getFileType() != null) {
            String deleteCacheKey1 = String.format(Constants.FILE_TYPE_LIST_CACHE_KEY,
                    messageDto.getUserId(), messageDto.getFileType());
            redisCache.deleteKeysByPattern(deleteCacheKey1);
        }
        String deleteCacheKey2 = String.format(Constants.FILE_TYPE_LIST_CACHE_KEY,
                messageDto.getUserId(), null);
        redisCache.deleteKeysByPattern(deleteCacheKey2);
        //判断是不是上传操作，是的话还要更新缓存中的用户剩余空间
        if (BusinessType.UPLOAD.toString().equals(messageDto.getMark())) {
            //更新用户剩余空间
            String useSpaceKey = String.format(RedisMessage.USER_SPACE_KEY, messageDto.getUserId().toString());
            Long useSpace = redisCache.getCacheMapValue(useSpaceKey, messageDto.getUserId().toString());
            redisCache.setCacheMapValue(useSpaceKey, messageDto.getUserId().toString(), useSpace + messageDto.getFileSize());
        }
    }
}